var status = 1 
var type = true
var tableData = [] 
var resultsSpatialData = [] // 应用分类数据  
if (sessionStorage.getItem('applicationOperationAudit_curr') != null) {
    sessionStorage.setItem('applicationOperationAudit_curr',1)
}
// 时间排序
function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}
function saveTableAudit() {
    let results = sendAjax(modelURL + "/apply/getRunApply", "POST", {
        userNo: portaluserno
    });  
    if (results.code == 200 ) { 
        results.data.sort(creatCompare("SAVEDATE"))
        tableData = results.data.map(item => { 
            return Object.assign(item,{
                APPLICATION_TYPE:'专题应用',
                // SAVEDATE:new Date(item.SAVEDATE).toISOString().replace("T", " ").replace(".000Z", "") 
                SAVEDATE:getYMDHMS (item.SAVEDATE) 
            })
        }) 
    } else {
        layer.msg('获取失败')
    }  
    let resultsSpatial = sendAjax(modelURL + "dict/getDataDict", "POST", { 
        name: 'spatial'
    });  
    if (resultsSpatial.code == 200) {
        resultsSpatialData = resultsSpatial.data
    }
    let resultsAnalysisType = sendAjax(modelURL + "dict/getDataDict", "POST", { 
        name: 'analysisType'
    });    
    tables ()   
    table.on('tool(audit_table)', function (obj) { 
        if (obj.event == 'audits') {  
            let auditsData 
            let results = resultFunction (obj) 
            if (results.code == 200 ) {
                auditsData = results.data
            } else {
                layer.msg('获取失败')
            }  
            $('#applicantReason').html(auditsData.reason)
            $('#auditsDivH3').html(obj.data.NAME)
            $('#applicant').val(obj.data.APPLYPERSON) 
            // let times = new Date(auditsData.savedate).toISOString().replace("T", " ").replace(".000Z", ""); 
            let times = getYMDHMS (auditsData.savedate) 
            $('#applicantTime').val(times) 
            $('#authorizationTime').val('2099-09-15 10:11:12') 
            layer.open({
                type: 1,
                title: "审核",
                shadeClose: true,
                content: $('#auditsDiv'),
                end: function (res) {
                    $("#auditsDiv").css("display", 'none');
                }
                ,btn: ['确定', '取消']
                ,yes: function(index){ 
                    if ($('#authorizationReason').val() != '') {
                        type = true 
                    } 
                    if (type) {
                        $('#audits').addClass('layui-btn-disabled')
                        $('#audits').attr('lay-event','')
                        $('#audits').html('已审核') 
                        let results = sendAjax(modelURL + "/apply/updateRunApply", "POST", {
                            id: obj.data.ID,
                            status,
                            opinion:$('#authorizationReason').val(), // 意见
                            approvalperson:portaluserno
                        });  
                        if (results.code == 200 ) { 
                            saveTableAudit () 
                            layer.close(index);  
                            allDataAudit () 
                            layer.msg(results.msg) 
                        } else {
                            layer.msg('获取失败')
                        } 
                    } else {
                        layer.msg('请填写审核意见') 
                    }
                    
                    // 通过 1
                    // 不通过 2 强制写理由 请填写审核意见 
                }
                ,btn2: function(index, layero){
                    layer.close(index); 
                }
            });
        } else if (obj.event == 'auditRecords') { 
            let auditsData 
            let results = resultFunction (obj) 
            if (results.code == 200 ) {
                auditsData = results.data
            } else {
                layer.msg('获取失败')
            } 
            $('#auditRecordsH3').html(obj.data.NAME) 
            let approvaldateTime = formatDate (auditsData.approvaldate)  // new Date(auditsData.approvaldate).toISOString().replace("T", " ").replace(".000Z", ""); 
            $('#auditRecordsTime').html(approvaldateTime) 
            $('#auditRecordsSH').html('应用运行申请') 
            if (auditsData.status == '1') {
                $('#auditRecordsJL').html('通过') 
            } else if (auditsData.status == '2') {
                $('#auditRecordsJL').html('不通过') 
            }   
            $('#auditRecordsYJ').html(auditsData.opinion) 
            // let times = new Date(obj.data.SAVEDATE).toISOString().replace("T", " ").replace(".000Z", "");  
            let times = getYMDHMS (obj.data.SAVEDATE) 
            $('#applicantTime').val(times) 
            $('#authorizationTime').val('2099-09-15 10:11:12') 
            layer.open({
                type: 1,
                title: "审核记录",
                shadeClose: true,
                content: $('#auditRecordsDiv'),
                end: function (res) {
                    $("#auditRecordsDiv").css("display", 'none');
                },
            });
        }
    }) 
    table.on('toolbar(audit_table)',function (obj) {
        if (obj.event == 'btn_search') {
            let timeNum = $('#ipt_date').val()
            let startTime = $.trim(timeNum.substring(0,10));
            let endTime = $.trim(timeNum.substring(13));
            let results = sendAjax(modelURL + "/apply/getRunApply", "POST", { 
                startTime,
                endTime, 
                applyPerson:$('#theApplicant').val(),
                name:$('#applicationName').val(),
                userNo:portaluserno
            });  
            if (results.code == 200) { 
                tableData = results.data  
                sessionStorage.setItem('applicationOperationAudit_curr',1)
                tableData.sort(creatCompare("SAVEDATE"))
                tableData = results.data.map(item => {
                    return Object.assign(item,{
                        APPLICATION_TYPE:'专题应用',
                        // SAVEDATE:new Date(item.SAVEDATE).toISOString().replace("T", " ").replace(".000Z", "") 
                        SAVEDATE:getYMDHMS (item.SAVEDATE) 
                    })
                }) 
                tables () 
            }
        } else if (obj.event == 'btn_reset') {
        sessionStorage.setItem('applicationOperationAudit_curr',1)
            $('#applicationName').val('')
            $('#theApplicant').val('') 
            $('#ipt_date').val('') 
            saveTableAudit () 
        }
    }) 
}  
function resultFunction (obj) { 
    let results
    results = sendAjax(modelURL + "/apply/getApplyInfo", "POST", {
        id: obj.data.ID
    }); 
    return results

} 
// 点击当前行弹框 
//点击弹出的“客户信息”弹层上的表格中“选中”按钮的触发函数
function department_tool_event_handler(obj) {
	console.info(obj);
	var data = obj.data;
	switch (obj.event) {
		case 'select':
			$('#dname').val(data.dname);
			layer.close(layer.index);
				break;
	}
}
// 时间戳转换时间年月日时分秒 
function getYMDHMS(timestamp) {
    let time = new Date(timestamp)
    let year = time.getFullYear()
    const month = (time.getMonth() + 1).toString().padStart(2, '0')
    const date = (time.getDate()).toString().padStart(2, '0')
    const hours = (time.getHours()).toString().padStart(2, '0')
    const minute = (time.getMinutes()).toString().padStart(2, '0')
    const second = (time.getSeconds()).toString().padStart(2, '0')

    return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
} 
function tables () {
    var name =  $('#applicationName').val()
    var dateTime =  $('#ipt_date').val()
    var theApplicantName =  $('#theApplicant').val()
    table.render({
        elem: '#audit_table',
        data: tableData,  
        toolbar:true,
        toolbar:'#headerDiv', 
        page: {
            limit:20,
            curr:sessionStorage.getItem('applicationOperationAudit_curr') ? sessionStorage.getItem('applicationOperationAudit_curr') : 1
        }, 
        done:function (res,curr,count) {
            sessionStorage.setItem('applicationOperationAudit_curr',curr)
            $("[data-field = 'NAME']").children().each(function () {
                if($(this).text() != "应用名称"){
                    $(this).addClass("linkTabTxtTag");
                }
            });
        }
        ,cols: [
            [ //表头
                {
                    type: 'numbers',
                    title: '序号',
                    sort: true,
                    width: 80,
                    align: "center"
                }, {
                    field: 'NAME',
                    title: '应用名称',
                    align: "center"
                }, {
                    field: 'APPLICATION_TYPE',
                    title: '应用类型',
                    align: "center"
                }, {
                    field: 'APPLYPERSON',
                    title: '申请人',
                    align: "center"
                },{
                    field: 'SAVEDATE',
                    title: '申请时间',
                    align: "center"
                },{
                    field: 'REASON',
                    title: '申请理由',
                    align: "center"
                },{
                    field: 'permission',
                    title: '操作',
                    toolbar: '#permissionAuditDiv',
                    align: "center"
                }
            ]
        ]
    }); 
    $(".linkTabTxtTag").each(function(index,dom){
        var data = null
        tableData.map(item => {
            if ($(dom).text() == item.NAME) {
                data = item 
                if (data != null){
                    if (data.STYLE == 2) {
                        $(dom).addClass("linkTabTxt");
                    }
                }
                return 
            }
        })
    });
    $('#applicationName').val(name)
    $('#ipt_date').val(dateTime)
    $('#theApplicant').val(theApplicantName) 
    laydate.render({
        elem: '#ipt_date'
        , type: 'date'
        , range: true
    }); 
    $('.layui-table-cell').click(function (e) {
        let text = e.target.innerText 
        let currentData = null 
        tableData.map(item => {
            if (text == item.NAME) {
                currentData = item 
                return 
            }
        }) 
        if (currentData != null) {
            if (currentData.STYLE == 2) {
                let dataById = sendAjax(modelURL + "apply/getApplyById", "POST", { 
                    id: currentData.APPLYID,
                    style: currentData.STYLE,
                });  
                let results = [] 
                if (typeof dataById == 'string') {
                    results = JSON.parse(dataById)
                } else {
                    results = dataById
                }
                if (results.code == 200) {   
                    $('#selectDatabase').val(results.data.databaseName)
                    $('#selectDatabaseTable').val(results.data.tableName)
                    // 分析工具
                    $('#analysisTools').val(results.data.analysisTools)
                    // 应用分类
                    resultsSpatialData.map(item => {
                        if (item.ZDVALUE == results.data.systemType) {
                            $('#applicationClassification').val(item.ZDTITLE)
                        }
                        return 
                    })  
                    $('.applicationName').val(results.data.name)
                    $('#description').val(results.data.description)
                }
                layer.open({
                    type: 1,
                    title: "详细信息",
                    shadeClose: true,
                    content: $('#detailedDiv'),
                    end: function (res) {
                        $("#detailedDiv").css("display", 'none');
                    }
                    ,btn: ['确定']
                    ,yes: function(index){ 
                        layer.close(index); 
                    }
                });
            } 
        }
    })
}
function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}  
function saveRadio() { 
    form.on('radio(jiedian)', function (data) {
        if (data.value == '通过') { 
            type = true
            status = 1 
        } else if (data.value == '不通过') { 
            type = false 
            status = 2 
        }
    }) 
}
function allDataAudit () {
    let results = sendAjax(modelURL + "/apply/getApplyCounts", "POST", {
    });   
    if (results.code == '200') {
        $('#allCount').html(results.data.allCount + '个')
        $('#waitCount').html(results.data.waitCount + '个')
        $('#Count').html(results.data.Count + '个')
    } else {
        layer.msg('获取失败')
    }
}     